using B.S.BaseData.Infrastructure;
using B.S.BaseData.Infrastructure.Implement;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x =>
{
    x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.BaseData.Write.API.xml", true);
});
//
/*builder.Services.AddDbContext<DBContext>(x =>
{
    x.UseSqlServer(builder.Configuration.GetConnectionString("DB"));
});*/
builder.Services.AddDbContext<DBContext>(p => p.UseMySql(builder.Configuration.GetConnectionString("DB"),
    new MySqlServerVersion(new Version(5, 7, 44))));

builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

builder.Services.AddAutoMapper(typeof(MappingProfile));

// 注册 SqlSugar 客户端服务
builder.Services.AddScoped<ISqlSugarClient>(provider =>
{
    // 获取配置服务
    var configuration = provider.GetRequiredService<IConfiguration>();
    // 获取数据库连接字符串
    string connectionString = configuration.GetConnectionString("DB");
    SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = connectionString, // 连接字符串
        DbType = DbType.MySql, // 数据库类型
        IsAutoCloseConnection = true, // 自动释放数据库连接
        InitKeyType = InitKeyType.Attribute // 从实体特性中读取主键自增信息
    });
    
    // 创建数据库（如果不存在）
    Db.DbMaintenance.CreateDatabase();
    
    // 打印到控制台
    Db.Aop.OnLogExecuting = (sql, pars) =>
    {
        Console.WriteLine($"执行SQL:{sql},参数:{sql}");
    };
    
    return Db;
});

var app = builder.Build();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    app.UseSwaggerUI();
//}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
